﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Media;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;

namespace Win7ThemeEditor
{
    public partial class MainWindow : Window
    {
        
        #region 初始化

        string definfo = "作者：\r\n网址：";
        string defRarInfo = "【安装提示】\r\n\r\n●请务必保证系统为Win7家庭高级版以上（包括专业版和旗舰版，不知道的可以到我的电脑右键属性里查看），并打过主题破解补丁和文件夹背景补丁。没打过补丁的请参阅下面的网址： http://bbs.comicdd.com/thread-199748-1-1.html \r\n\r\n●此安装包为直装版，需要删除的请在个性化设置里右键删除。\r\n\r\n●下面的路径无需更改，直接安装即可！";
        string defAboutInfo = "Copyright 2011-2012 樱茶幻萌组@桂叶出品\n樱茶Win7主题生成器 " + Share.VER + "\n本软件可自由传播使用，在没有得到作者或樱茶幻萌组授权的情况下禁止用于任何商业用途，最终解释权归樱茶幻萌组与作者\n软件作者：桂叶君    最后更新：2012-7-5";
        string themeFile = "";
        string openTheme = "";
        string openThemeDir = "";
        int[] sliderTime = { 10000, 30000, 60000, 180000, 300000, 600000, 900000, 1200000, 1800000, 3600000, 7200000, 10800000, 14400000, 21600000, 43200000, 86400000 };
        string[] cbSysWaveDefaultNum = { "800", "801", "810", "811", "812", "813", "814", "815", "816", "817", "818", "819", "820", "821", "822" };
        string tempDir = Environment.CurrentDirectory + @"\Res\Tools\WinRAR\Temp\";
        string tempDir2 = Environment.CurrentDirectory + @"\Res\Tools\WinRAR\Temp2\";
        string rarPath = Environment.CurrentDirectory + @"\Res\Tools\WinRAR\Rar.exe";
        string currentDir = System.Environment.CurrentDirectory;
        string tempDir3 = Environment.CurrentDirectory + @"\Temp\";
        string sysThemeDir = Environment.GetEnvironmentVariable("windir") + @"\Resources\Themes\";
        bool isAnimated = true;

        //定义用代码启动的 Storyboard
        Storyboard sbBegin, sbNewTheme, HideOpenThemeFileWindow, ShowPicViewWindow, ShowErrorWindowSB, SakuraFade, sbNanaSpin, sbBigHnaSpin, sbSaveRarOpen, sbSaveRarClose;

        //可通知绑定的集合
        ObservableCollection<SysWaveItems> sysWaveItems = new ObservableCollection<SysWaveItems>();
        ObservableCollection<sysThemeFileItems> themeDirFileItems = new ObservableCollection<sysThemeFileItems>();
        ObservableCollection<WallpaperItems> wps = new ObservableCollection<WallpaperItems>();

        //入口
        public MainWindow()
        {
            InitializeComponent();
        }

        //载入完成
        private void GlassWindow_Loaded(object sender, RoutedEventArgs e)
        {

            if (DWMHelper.ExtendAeroGlass(this))
            {
                this.Background = Brushes.Transparent;
            }
            else
            {
                this.Background = System.Windows.Media.Brushes.White;
            }

            InitShadow();
            InitWaveItems();
            setDefault();
            InitWindow();
            InitVisibility();
            InitStoryboard();
            InitBinding();
            InitEvent();

            if (Share.IsOverwriteSave)
            {
                readConfig();
                writeFile();
                save2();
                string tempThemename = tbFileName.Text;
                setDefault();
                openThemeDir = sysThemeDir + tempThemename + ".theme";
                openTheme = File.ReadAllText(openThemeDir, Encoding.Default);
                readThemeFile();

            }
            else
            {
                sbBegin.Begin();
            }




        }

        //各种初始化
        void InitShadow()
        {
            DropShadowEffect objDropShadow = new DropShadowEffect();
            objDropShadow.ShadowDepth = 0;
            objDropShadow.BlurRadius = 10;
            objDropShadow.Color = Colors.White;
            foreach (UIElement ue in MainPanel.Children)
            {
                //if(ue is TextBox)
                ue.Effect = objDropShadow;
            }
            foreach (UIElement ue in canvasAbout.Children)
            {
                ue.Effect = objDropShadow;
            }
            foreach (UIElement ue in OpenFileGrid.Children)
            {
                ue.Effect = objDropShadow;
            }
        }//初始化阴影
        void InitBinding()//初始化数据绑定
        {
            listboxWallpaperItems.ItemsSource = wps; //设置壁纸listbox源为wps
            listboxOpenTheme.ItemsSource = themeDirFileItems;
            listboxSysWaveItems.ItemsSource = sysWaveItems;
        }
        void InitWindow()//初始化窗口
        {
            winMain.Title = "Win7主题生成器 V" + Share.VER + "（樱茶幻萌组专用）";
            lbInfo.Text = defAboutInfo;
            if (!Share.IsAdmin())
            {
                MessageBox.Show("检测到非管理员权限，若要启用保存到系统主题目录功能，请使用管理员身份运行本程序");
                btnSave.IsEnabled = false;

            }

            detectWallpaperNum();
        }
        void InitVisibility()//初始化各个层次可见性
        {
            winMain.canvasSaveRAR.Visibility = Visibility.Hidden;//初始化rar保存canvas
            canvasAbout.Visibility = Visibility.Hidden;//初始化关于canvas
            canvasPicView.Visibility = Visibility.Hidden;
            canvasError.Visibility = Visibility.Hidden;
            OpenFileGrid.Visibility = Visibility.Hidden;
        }
        void InitStoryboard()//指向Storyboard,并在初期启动
        {
            ShowPicViewWindow = (Storyboard)Resources["ShowPicViewWindow"];
            ShowErrorWindowSB = (Storyboard)Resources["ShowErrorWindow"];
            HideOpenThemeFileWindow = (Storyboard)Resources["HideOpenThemeFileWindow"];
            sbNewTheme = (Storyboard)Resources["sbNewTheme"];
            sbBegin = (Storyboard)Resources["sbBegin"];

            SakuraFade = (Storyboard)Resources["SakuraFade"]; 
            sbNanaSpin = (Storyboard)Resources["sbNanaSpin"]; 
            sbBigHnaSpin = (Storyboard)Resources["sbBigHnaSpin"]; 

            sbSaveRarOpen = (Storyboard)Resources["sbSaveRarOpen"];
            sbSaveRarClose = (Storyboard)Resources["sbSaveRarClose"];

            SakuraFade.Begin();
            sbNanaSpin.Begin();
            sbBigHnaSpin.Begin();
            AppSetting appSetting = new AppSetting();
            if(!appSetting.IsAnimateRun)
            {
                sbNanaSpin.Pause();
                sbBigHnaSpin.Pause();
                SakuraFade.Pause();
                isAnimated = false;
                appSetting.IsAnimateRun = false;
                appSetting.Save();
            }
            
        }
        void FindSBRes(Storyboard sb)
        {
            sb = (Storyboard)Resources[sb.Name];
        }
        void InitEvent()//初始化事件
        {
            //壁纸
            listboxWallpaperItems.DragEnter += new DragEventHandler(listboxWallpaperItems_DragEnter);
            listboxWallpaperItems.Drop += new DragEventHandler(listboxWallpaperItems_Drop);
            listboxWallpaperItems.KeyDown += new KeyEventHandler(listboxWallpaperItems_KeyDown);

            wps.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(wps_CollectionChanged);
            
            
        }

        
        void InitWaveItems()//初始化系统声音信息
        {
            //windows
            sysWaveItems.Add(new SysWaveItems { DispName = "Windows更改主题（常用）", IniName = @"AppEvents\Schemes\Apps\.Default\ChangeTheme" });
            sysWaveItems.Add(new SysWaveItems { DispName = "Windows注销（常用）", IniName = @"AppEvents\Schemes\Apps\.Default\WindowsLogoff" });
            sysWaveItems.Add(new SysWaveItems { DispName = "Windows用户账户控制", IniName = @"AppEvents\Schemes\Apps\.Default\WindowsUAC" });
            sysWaveItems.Add(new SysWaveItems { DispName = "Windows登录（常用）", IniName = @"AppEvents\Schemes\Apps\.Default\WindowsLogon" });
            sysWaveItems.Add(new SysWaveItems { DispName = "关键性停止", IniName = @"AppEvents\Schemes\Apps\.Default\SystemHand" });
            sysWaveItems.Add(new SysWaveItems { DispName = "关闭程序", IniName = @"AppEvents\Schemes\Apps\.Default\Close" });
            sysWaveItems.Add(new SysWaveItems { DispName = "向上还原", IniName = @"AppEvents\Schemes\Apps\.Default\RestoreUp" });
            sysWaveItems.Add(new SysWaveItems { DispName = "向下还原", IniName = @"AppEvents\Schemes\Apps\.Default\RestoreDown" });
            sysWaveItems.Add(new SysWaveItems { DispName = "弹出菜单", IniName = @"AppEvents\Schemes\Apps\.Default\MenuPopup" });
            sysWaveItems.Add(new SysWaveItems { DispName = "感叹号", IniName = @"AppEvents\Schemes\Apps\.Default\SystemExclamation" });
            sysWaveItems.Add(new SysWaveItems { DispName = "打印结束", IniName = @"AppEvents\Schemes\Apps\.Default\PrintComplete" });
            sysWaveItems.Add(new SysWaveItems { DispName = "打开程序", IniName = @"AppEvents\Schemes\Apps\.Default\Open" });
            sysWaveItems.Add(new SysWaveItems { DispName = "新传真通知", IniName = @"AppEvents\Schemes\Apps\.Default\FaxBeep" });
            sysWaveItems.Add(new SysWaveItems { DispName = "新邮件通知", IniName = @"AppEvents\Schemes\Apps\.Default\MailBeep" });
            sysWaveItems.Add(new SysWaveItems { DispName = "星号", IniName = @"AppEvents\Schemes\Apps\.Default\SystemAsterisk" });
            sysWaveItems.Add(new SysWaveItems { DispName = "显示工具栏区", IniName = @"AppEvents\Schemes\Apps\.Default\ShowBand" });
            sysWaveItems.Add(new SysWaveItems { DispName = "最大化", IniName = @"AppEvents\Schemes\Apps\.Default\Maximize" });
            sysWaveItems.Add(new SysWaveItems { DispName = "最小化", IniName = @"AppEvents\Schemes\Apps\.Default\Minimize" });
            sysWaveItems.Add(new SysWaveItems { DispName = "电池不足警报", IniName = @"AppEvents\Schemes\Apps\.Default\LowBatteryAlarm" });
            sysWaveItems.Add(new SysWaveItems { DispName = "电池严重不足警报", IniName = @"AppEvents\Schemes\Apps\.Default\CriticalBatteryAlarm" });
            sysWaveItems.Add(new SysWaveItems { DispName = "程序错误", IniName = @"AppEvents\Schemes\Apps\.Default\AppGPFault" });
            sysWaveItems.Add(new SysWaveItems { DispName = "系统通知", IniName = @"AppEvents\Schemes\Apps\.Default\SystemNotification" });
            sysWaveItems.Add(new SysWaveItems { DispName = "菜单命令", IniName = @"AppEvents\Schemes\Apps\.Default\MenuCommand" });
            sysWaveItems.Add(new SysWaveItems { DispName = "设备中断连接", IniName = @"AppEvents\Schemes\Apps\.Default\DeviceDisconnect" });
            sysWaveItems.Add(new SysWaveItems { DispName = "设备未能连接", IniName = @"AppEvents\Schemes\Apps\.Default\DeviceFail" });
            sysWaveItems.Add(new SysWaveItems { DispName = "设备连接", IniName = @"AppEvents\Schemes\Apps\.Default\DeviceConnect" });
            sysWaveItems.Add(new SysWaveItems { DispName = "退出Windows（常用）", IniName = @"AppEvents\Schemes\Apps\.Default\SystemExit" });
            sysWaveItems.Add(new SysWaveItems { DispName = "选择", IniName = @"AppEvents\Schemes\Apps\.Default\CCSelect" });
            sysWaveItems.Add(new SysWaveItems { DispName = "问题", IniName = @"AppEvents\Schemes\Apps\.Default\SystemQuestion" });
            sysWaveItems.Add(new SysWaveItems { DispName = "默认响声", IniName = @"AppEvents\Schemes\Apps\.Default\.Default" });

            //windows资源管理器
            sysWaveItems.Add(new SysWaveItems { DispName = "传真错误", IniName = @"AppEvents\Schemes\Apps\Explorer\FaxError" });
            sysWaveItems.Add(new SysWaveItems { DispName = "信息栏", IniName = @"AppEvents\Schemes\Apps\Explorer\SecurityBand" });
            sysWaveItems.Add(new SysWaveItems { DispName = "启动导航", IniName = @"AppEvents\Schemes\Apps\Explorer\Navigating" });
            sysWaveItems.Add(new SysWaveItems { DispName = "完成导航", IniName = @"AppEvents\Schemes\Apps\Explorer\ActivatingDocument" });
            sysWaveItems.Add(new SysWaveItems { DispName = "已发现搜索提供程序", IniName = @"AppEvents\Schemes\Apps\Explorer\SearchProviderDiscovered" });
            sysWaveItems.Add(new SysWaveItems { DispName = "已发现原", IniName = @"AppEvents\Schemes\Apps\Explorer\FeedDiscovered" });
            sysWaveItems.Add(new SysWaveItems { DispName = "已发送传真", IniName = @"AppEvents\Schemes\Apps\Explorer\FaxSent" });
            sysWaveItems.Add(new SysWaveItems { DispName = "拨入电话", IniName = @"AppEvents\Schemes\Apps\Explorer\FaxLineRings" });
            sysWaveItems.Add(new SysWaveItems { DispName = "请空回收站（常用）", IniName = @"AppEvents\Schemes\Apps\Explorer\EmptyRecycleBin" });
            sysWaveItems.Add(new SysWaveItems { DispName = "移动菜单项", IniName = @"AppEvents\Schemes\Apps\Explorer\MoveMenuItem" });
            sysWaveItems.Add(new SysWaveItems { DispName = "阻止弹出的窗口", IniName = @"AppEvents\Schemes\Apps\Explorer\BlockedPopup" });

        }


        #endregion

        #region 方法

        /// <summary>
        /// 显示错误
        /// </summary>
        /// <param name="errStr">错误信息</param>
        private void showErrorWindow(string errStr)
        {
            tbError.Text = errStr;
            ShowErrorWindowSB.Begin();
        }

        /// <summary>
        /// 文件选择对话框，显示路径
        /// </summary>
        /// <param name="tb">显示路径的TextBox</param>
        /// <param name="ext">文件类型</param>
        private void fileDialogDir(TextBox tb, string ext)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.RestoreDirectory = true;
            switch (ext)
            {
                case "cur":
                    op.Filter = "指针图像文件cur,ani|*.cur;*.ani"; break;
                case "ico":
                    op.Filter = "ICO文件|*.ico"; break;
                case "jpg":
                    op.Filter = "图像文件(JPG)|*.jpg|所有文件(*.*)|*.*"; break;
                case "png":
                    op.Filter = "图像文件(PNG)|*.png|所有文件(*.*)|*.*"; break;
                case "img":
                    op.Filter = "图像文件(jpg,png,bmp,gif)|*.png;*.jpg;*.bmp;*.gif|所有文件(*.*)|*.*"; break;
                case "mss":
                    op.Filter = "主题样式文件(*.Msstyles)|*.msstyles"; break;
                case "wav":
                    op.Filter = "波形文件Wav|*.wav"; break;
                default:
                    return;

            }
            op.ShowDialog();
            if (op.FileName != "")
            {
                tb.Text = op.FileName;
                if (ext == "cur")
                {
                    System.Windows.Input.Cursor cur = new System.Windows.Input.Cursor(op.FileName);
                    tb.Cursor = cur;
                }
            }
        }

        //添加壁纸，显示路径
        private void addWallpaper()
        {
            OpenFileDialog op = new OpenFileDialog();
            op.RestoreDirectory = true;
            op.Multiselect = true;
            op.Filter = "图像文件(jpg,png,bmp,gif)|*.jpg;*.png;*.bmp;*.gif|所有文件(*.*)|*.*";
            op.ShowDialog();
            if (op.FileName != "")
            {
                foreach (string name in op.FileNames)
                {
                    if(!containWpsFile(name))
                        wps.Add(new WallpaperItems { Name = name, Pic = name });

                }
            }
        }

        /// <summary>
        /// 壁纸数量或位置变化时的操作
        /// </summary>
        private void detectWallpaperNum()
        {
            
            if (wps.Count > 1)
            {
                cbWallpaperTime.IsEnabled = true;
                cbShuffle.IsEnabled = true;
            }
            else
            {
                cbWallpaperTime.IsEnabled = false;
                cbShuffle.IsEnabled = false;
            }

            switch(wps.Count)
            {
                case 0:
                    setThemeIconWallpaper(Environment.GetEnvironmentVariable("windir") + @"\Web\Wallpaper\Windows\img0.jpg", "", "", "");
                    break;
                case 1:
                    setThemeIconWallpaper(wps[0].Name, "", "", "");
                    break;
                case 2:
                    setThemeIconWallpaper("", wps[0].Name, wps[1].Name, "");
                    break;
                case 3:
                    setThemeIconWallpaper("", wps[0].Name, wps[1].Name, wps[2].Name);
                    break;
                default:
                    setThemeIconWallpaper("", wps[0].Name, wps[1].Name, wps[2].Name);
                    break;
            }
        }
        private void setThemeIconWallpaper(string str0,string str1,string str2,string str3)
        {
            setImage(ThemeIconWP0, str0);
            setImage(ThemeIconWP1, str1);
            setImage(ThemeIconWP2, str2);
            setImage(ThemeIconWP3, str3);
        }

        /// <summary>
        /// 设置新建
        /// </summary>
        public void setDefault()
        {
            try
            {
                sbNewTheme.Begin();
            }
            catch { }
            //基本信息
            tbMssfileDir.Text = "";
            tbLogoDir.Text = Share.defimg;
            tbInfo.Text = definfo;
            if (File.Exists(sysThemeDir + "Aero\\aero.msstyles"))
                tbMssfileDir.Text = sysThemeDir + "Aero\\aero.msstyles";
            tbThemeName.Text = "我的主题";
            tbFileName.Text = "My Theme";

            //系统图标
            tbIconComputertfileDir.Text = Share.defico;
            tbIconUserDir.Text = Share.defico;
            tbIconNetworkDir.Text = Share.defico;
            tbIconDustEmptyDir.Text = Share.defico;
            tbIconDustFullDir.Text = Share.defico;

            //系统指针
            for (int i = 1; i <= 15; i++)
            {
                ((TextBox)FindName("tbcur" + i.ToString())).Text = Share.defcur;
            }
            tbcur1.Cursor = System.Windows.Input.Cursors.AppStarting;
            tbcur2.Cursor = System.Windows.Input.Cursors.Arrow;
            tbcur3.Cursor = System.Windows.Input.Cursors.Cross;
            tbcur4.Cursor = System.Windows.Input.Cursors.Hand;
            tbcur5.Cursor = System.Windows.Input.Cursors.Help;
            tbcur6.Cursor = System.Windows.Input.Cursors.IBeam;
            tbcur7.Cursor = System.Windows.Input.Cursors.No;
            tbcur8.Cursor = System.Windows.Input.Cursors.Pen;
            tbcur9.Cursor = System.Windows.Input.Cursors.SizeAll;
            tbcur10.Cursor = System.Windows.Input.Cursors.SizeNESW;
            tbcur11.Cursor = System.Windows.Input.Cursors.SizeNS;
            tbcur12.Cursor = System.Windows.Input.Cursors.SizeNWSE;
            tbcur13.Cursor = System.Windows.Input.Cursors.SizeWE;
            tbcur14.Cursor = System.Windows.Input.Cursors.UpArrow;
            tbcur15.Cursor = System.Windows.Input.Cursors.Wait;


            //背景壁纸

            wps.Clear();
            cbWallpaperTime.SelectedIndex = 5;
            cbWallpaperTime.IsEnabled = false;
            cbShuffle.IsChecked = false;
            cbShuffle.IsEnabled = false;

            //颜色
            spectrumColorPicker.SelectedColor = (Color)ColorConverter.ConvertFromString(Share.defcolor);


            //系统音
            for (int i = 0; i < sysWaveItems.Count; i++)
            {
                sysWaveItems[i].Custom = "0";
                sysWaveItems[i].Path = null;
            }
            listboxSysWaveItems.Items.Refresh();
            chboxDefwav.IsChecked = true;
            cbSysWaveDefault.SelectedIndex = 0;
            enableWave(false);

            //自解压框
            checkboxSaveRarKey.IsChecked = false;
            tbSaveRarKey.IsEnabled = false;
            tbSaveRarKey.Text = "";
            tbSaveRarInfo.Text = defRarInfo;
            checkboxSaveRarAutoRun.IsChecked = false;
            tbSaveRarTitle.Text = "";

        }

        /// <summary>
        /// 非法名称除错
        /// </summary>
        /// <param name="tb">传入的Textbox</param>
        private void replaceFileName(TextBox tb)
        {
            tb.Text = tb.Text.Replace(";", "").Replace(":", "").Replace("<", "").Replace(">", "").Replace("*", "").Replace("?", "").Replace("\\", "").Replace("/", "").Replace("|", "").Replace("\"", "").Replace("[", "").Replace("]", "").Replace(";", "");
        }

        /// <summary>
        /// 显示图标、图片
        /// </summary>
        /// <param name="img">图像源</param>
        /// <param name="path">图像路径</param>
        private void setImage(Image img, string path)
        {
            if (path == "")
            {
                img.Source = null;
            }
            else if (path == Share.defico)
            {
                if (img == icoComputer)
                {
                    icoComputer.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/Computer.png", UriKind.Relative));
                }
                else if (img == icoUserFile)
                {
                    icoUserFile.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/UserFile.png", UriKind.Relative));
                }
                else if (img == icoNetwork)
                    icoNetwork.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/Network.png", UriKind.Relative));
                else if (img == icoDustEmpty)
                    icoDustEmpty.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/DustEmpty.png", UriKind.Relative));
                else if (img == icoDustFull)
                    icoDustFull.Source = new BitmapImage(new Uri("/Win7ThemeEditor;component/Res/Icon/DustFull.png", UriKind.Relative));
            }
            else
            {
                try
                {
                    img.Source = new BitmapImage(new Uri(path, UriKind.Absolute));
                }
                catch { }
            }
        }

        //打开theme文件
        private void openThmeFile()
        {
            DirectoryInfo dir = new DirectoryInfo(sysThemeDir);
            FileInfo[] files = (dir).GetFiles();
            themeDirFileItems.Clear();
            foreach (FileInfo file in files)
            {
                if (Path.GetExtension(file.FullName.ToLower()) == ".theme")
                {
                    var ini = new Class.IniFile(file.FullName);
                    string FullNameTemp = "";
                    string DisplayName = ini.ReadInivalue("Theme", "DisplayName");
                    FullNameTemp += "文件名：" + file.Name + "\n";
                    if (DisplayName != "")
                        FullNameTemp += "主题名称：" + ini.ReadInivalue("Theme", "DisplayName");
                    string imgFile = relpaceSr(ini.ReadInivalue(@"Control Panel\Desktop", "Wallpaper"));
                    if (!File.Exists(imgFile))
                        imgFile = null;
                    if (DisplayName.IndexOf("themeui.dll") == -1)
                    {

                        themeDirFileItems.Add(new sysThemeFileItems { FullName = file.FullName, SName = FullNameTemp, ImgName = imgFile });


                    }
                }


            }
        }

        //写入Theme文件内容
        private void addLine(string line)
        {
            themeFile += (line + "\r\n");
        }
        private void writeFile()
        {
            string themeName = tbFileName.Text;
            themeFile = "";
            //主题信息
            addLine(";此主题文件由樱茶Win7主题生成器生成");
            addLine(";" + tbInfo.Text.Replace("\r\n", "\r\n;"));
            addLine("");
            addLine("[Theme]\r\n; Windows 7 - IDS_THEME_DISPLAYNAME_AERO");
            addLine("DisplayName=" + tbThemeName.Text);
            if (tbLogoDir.Text != Share.defimg) addLine(@"BrandImage=%SystemRoot%\Resources\Themes\" + themeName + @"\Logo.png");
            addLine("");

            //icon
            addLine("; Computer - SHIDI_SERVER\r\n[CLSID\\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\\DefaultIcon]");
            if (tbIconComputertfileDir.Text != Share.defico)
                addLine(@"DefaultValue=%SystemRoot%\resources\themes\" + themeName + @"\Icon\Computer.ico");
            else
                addLine(@"DefaultValue=%SystemRoot%\System32\imageres.dll,-109");
            addLine("");
            addLine("; UsersFiles - SHIDI_USERFILES\r\n" + @"[CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon]");
            if (tbIconUserDir.Text != Share.defico)
                addLine(@"DefaultValue=%SystemRoot%\resources\themes\" + themeName + @"\Icon\UsersFiles.ico");
            else
                addLine(@"DefaultValue=%SystemRoot%\System32\imageres.dll,-123");
            addLine("");
            addLine("; Network - SHIDI_MYNETWORK\r\n" + @"[CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon]");
            if (tbIconNetworkDir.Text != Share.defico)
                addLine(@"DefaultValue=%SystemRoot%\resources\themes\" + themeName + @"\Icon\Network.ico");
            else
                addLine(@"DefaultValue=%SystemRoot%\System32\imageres.dll,-25");
            addLine(@"; Recycle Bin - SHIDI_RECYCLERFULL SHIDI_RECYCLER");
            addLine(@"[CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon]");
            if (tbIconDustFullDir.Text == Share.defico)
                addLine(@"Full=%SystemRoot%\System32\imageres.dll,-54");
            else
                addLine(@"Full=%SystemRoot%\resources\themes\" + themeName + @"\Icon\RecycleFull.ico");
            if (tbIconDustEmptyDir.Text == Share.defico)
                addLine(@"Empty=%SystemRoot%\System32\imageres.dll,-55");
            else
                addLine(@"Empty=%SystemRoot%\resources\themes\" + themeName + @"\Icon\RecycleEmpty.ico");
            addLine("");

            //Cursors
            addLine(@"[Control Panel\Cursors]");
            if (tbcur1.Text == Share.defcur)
                addLine(@"AppStarting=%SystemRoot%\cursors\aero_working.ani");
            else
                addLine(@"AppStarting=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\AppStarting" + Path.GetExtension(tbcur1.Text));
            if (tbcur2.Text == Share.defcur)
                addLine(@"Arrow=%SystemRoot%\cursors\aero_arrow.cur");
            else
                addLine(@"Arrow=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Arrow" + Path.GetExtension(tbcur2.Text));
            if (tbcur3.Text == Share.defcur)
                addLine(@"Crosshair=");
            else
                addLine(@"Crosshair=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Crosshair" + Path.GetExtension(tbcur3.Text));
            if (tbcur4.Text == Share.defcur)
                addLine(@"Hand=%SystemRoot%\cursors\aero_link.cur");
            else
                addLine(@"Hand=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Hand" + Path.GetExtension(tbcur2.Text));
            if (tbcur5.Text == Share.defcur)
                addLine(@"Help=%SystemRoot%\cursors\aero_helpsel.cur");
            else
                addLine(@"Help=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Help" + Path.GetExtension(tbcur5.Text));
            if (tbcur6.Text == Share.defcur)
                addLine(@"IBeam=");
            else
                addLine(@"IBeam=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\IBeam" + Path.GetExtension(tbcur6.Text));
            if (tbcur7.Text == Share.defcur)
                addLine(@"No=%SystemRoot%\cursors\aero_unavail.cur");
            else
                addLine(@"No=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\No" + Path.GetExtension(tbcur7.Text));
            if (tbcur8.Text == Share.defcur)
                addLine(@"NWPen=%SystemRoot%\cursors\aero_pen.cur");
            else
                addLine(@"NWPen=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\NWPen" + Path.GetExtension(tbcur8.Text));
            if (tbcur9.Text == Share.defcur)
                addLine(@"SizeAll=%SystemRoot%\cursors\aero_move.cur");
            else
                addLine(@"SizeAll=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeAll" + Path.GetExtension(tbcur9.Text));
            if (tbcur10.Text == Share.defcur)
                addLine(@"SizeNESW=%SystemRoot%\cursors\aero_nesw.cur");
            else
                addLine(@"SizeNESW=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeNESW" + Path.GetExtension(tbcur10.Text));
            if (tbcur11.Text == Share.defcur)
                addLine(@"SizeNS=%SystemRoot%\cursors\aero_ns.cur");
            else
                addLine(@"SizeNS=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeNS" + Path.GetExtension(tbcur11.Text));
            if (tbcur12.Text == Share.defcur)
                addLine(@"SizeNWSE=%SystemRoot%\cursors\aero_nwse.cur");
            else
                addLine(@"SizeNWSE=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeNWSE" + Path.GetExtension(tbcur12.Text));
            if (tbcur13.Text == Share.defcur)
                addLine(@"SizeWE=%SystemRoot%\cursors\aero_ew.cur");
            else
                addLine(@"SizeWE=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\SizeWE" + Path.GetExtension(tbcur13.Text));
            if (tbcur14.Text == Share.defcur)
                addLine(@"UpArrow=%SystemRoot%\cursors\aero_up.cur");
            else
                addLine(@"UpArrow=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\UpArrow" + Path.GetExtension(tbcur14.Text));
            if (tbcur15.Text == Share.defcur)
                addLine(@"Wait=%SystemRoot%\cursors\aero_busy.ani");
            else
                addLine(@"Wait=%SystemRoot%\Resources\Themes\" + themeName + @"\Cursors\Wait" + Path.GetExtension(tbcur15.Text));
            addLine(@"DefaultValue=" + themeName + " Cursors");
            addLine(@"DefaultValue.MUI=@main.cpl,-1020");
            addLine("");

            //wallpaper
            addLine(@"[Control Panel\Desktop]");
            if (wps.Count == 0)
                addLine(@"Wallpaper=%SystemRoot%\web\wallpaper\Windows\img0.jpg");
            else
                addLine(@"Wallpaper=%SystemRoot%\Resources\Themes\" + themeName + @"\Wallpapers\0" + Path.GetExtension(wps[0].Name));
            addLine(@"TileWallpaper=0");
            addLine("WallpaperStyle=10");
            addLine("Pattern=");
            addLine("");

            //mss
            addLine("[VisualStyles]");
            addLine(@"Path=%SystemRoot%\resources\Themes\" + themeName + @"\" + themeName + ".msstyles");
            addLine("ColorStyle=NormalColor");
            addLine("Size=NormalSize");
            addLine("ColorizationColor=" + tbColorStr.Text.Replace("#", "0x"));
            addLine("Transparency=1");
            addLine("VisualStyleVersion=10");
            addLine("Composition=1");
            addLine("");
            addLine("[boot]\r\nSCRNSAVE.EXE=\r\n\r\n[MasterThemeSelector]\r\nMTSM=DABJDKT\r\n");

            //sound
            addLine("[Sounds]");
            if (chboxDefwav.IsChecked == true)
            {
                addLine("SchemeName=@%SystemRoot%\\System32\\mmres.dll,-" + cbSysWaveDefaultNum[cbSysWaveDefault.SelectedIndex]);
            }
            else
            {
                addLine("SchemeName=" + themeName + " Sound");
                for (int i = 0; i < sysWaveItems.Count; i++)
                {
                    if (sysWaveItems[i].Path != null && sysWaveItems[i].Path != "")
                    {
                        addLine("[" + sysWaveItems[i].IniName + "]");
                        addLine(@"DefaultValue=%SystemRoot%\Resources\Themes\" + themeName + @"\Sound\" + sysWaveItems[i].IniName.Remove(0, sysWaveItems[i].IniName.LastIndexOf("\\") + 1).Replace(".", "") + ".wav");
                    }
                }

            }

            addLine("");

            //slideshow
            if (wps.Count > 1)
            {

                addLine("[Slideshow]");
                addLine("Interval=" + sliderTime[cbWallpaperTime.SelectedIndex]);
                addLine("Shuffle=" + ((cbShuffle.IsChecked == true) ? "1" : "0"));
                addLine(@"ImagesRootPath=%SystemRoot%\resources\Themes\" + themeName + @"\Wallpapers");
            }


        }

        //复制文件操作
        private void copyFile(string pathFrom, string pathTo, bool isOverwrite)
        {
            FileInfo fi = new FileInfo(pathFrom);
            //判断文件属性是否只读?是则修改为一般属性再操作
            if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
            {
                fi.Attributes = FileAttributes.Normal;
            }
            File.Copy(pathFrom, pathTo, isOverwrite);
        }
        private void creatDir(string dir)
        {
            DirectoryInfo maindir = new DirectoryInfo(dir);
            if (!maindir.Exists)
                maindir.Create();
        }
        public bool IsUsed(string fileName)
        {
            bool result = false;

            try
            {
                FileStream fs = File.OpenWrite(fileName);
                fs.Close();
            }
            catch
            {
                result = true;
            }
            return result;
        }// 判断文件是否被其他程序占用
        private bool fileOperate(string themeSaveDir)
        {
            //themeSaveDir = @"D:\Develop\Test\";//测试用
            string enname = tbFileName.Text;

            string themeDir = themeSaveDir + enname + @"\";

            DirectoryInfo diThemeDir = new DirectoryInfo(themeDir);

            try
            {
                //目录创建，固定文件
                creatDir(themeDir + @"Cursors\");
                creatDir(themeDir + @"Wallpapers\");
                creatDir(themeDir + @"Icon\");
                creatDir(themeDir + @"Sound\");
                creatDir(themeDir + @"en-US\");
                creatDir(themeDir + @"Shell\NormalColor\en-US\");
                creatDir(themeDir + @"Shell\NormalColor\zh-CN\");
                creatDir(themeDir + @"zh-CN\");
                copyFile(currentDir + @"\Res\File\shellstyle.dll", themeDir + @"Shell\NormalColor\shellstyle.dll", true);
                copyFile(currentDir + @"\Res\File\shellstyle.dll.mui", themeDir + @"Shell\NormalColor\zh-CN\shellstyle.dll.mui", true);
                copyFile(currentDir + @"\Res\File\aero.msstyles.mui", themeDir + @"zh-CN\" + enname + ".msstyles.mui", true);

                //Mss、Theme、logo文件
                string FILE_NAME = themeSaveDir + enname + ".theme";
                using (StreamWriter sw = new StreamWriter(new FileStream(FILE_NAME, FileMode.Create), System.Text.Encoding.Default))
                {
                    sw.Write(themeFile);
                    sw.Close();
                }
                copyFile(tbMssfileDir.Text, themeDir + enname + ".msstyles", true);
                if (tbLogoDir.Text != Share.defimg)
                    copyFile(tbLogoDir.Text, themeDir + "Logo.png", true);


                //Icon
                if (tbIconComputertfileDir.Text != Share.defico)
                    copyFile(tbIconComputertfileDir.Text, themeDir + @"Icon\Computer.ico", true);
                if (tbIconUserDir.Text != Share.defico)
                    copyFile(tbIconUserDir.Text, themeDir + @"Icon\UsersFiles.ico", true);
                if (tbIconNetworkDir.Text != Share.defico)
                    copyFile(tbIconNetworkDir.Text, themeDir + @"Icon\Network.ico", true);
                if (tbIconDustEmptyDir.Text != Share.defico)
                    copyFile(tbIconDustEmptyDir.Text, themeDir + @"Icon\RecycleEmpty.ico", true);
                if (tbIconDustFullDir.Text != Share.defico)
                    copyFile(tbIconDustFullDir.Text, themeDir + @"Icon\RecycleFull.ico", true);

                //Cursors
                if (tbcur1.Text != Share.defcur)
                    copyFile(tbcur1.Text, themeDir + @"Cursors\AppStarting" + Path.GetExtension(tbcur1.Text), true);
                if (tbcur2.Text != Share.defcur)
                    copyFile(tbcur2.Text, themeDir + @"Cursors\Arrow" + Path.GetExtension(tbcur2.Text), true);
                if (tbcur3.Text != Share.defcur)
                    copyFile(tbcur3.Text, themeDir + @"Cursors\Crosshair" + Path.GetExtension(tbcur3.Text), true);
                if (tbcur4.Text != Share.defcur)
                    copyFile(tbcur4.Text, themeDir + @"Cursors\Hand" + Path.GetExtension(tbcur4.Text), true);
                if (tbcur5.Text != Share.defcur)
                    copyFile(tbcur5.Text, themeDir + @"Cursors\Help" + Path.GetExtension(tbcur5.Text), true);
                if (tbcur6.Text != Share.defcur)
                    copyFile(tbcur6.Text, themeDir + @"Cursors\IBeam" + Path.GetExtension(tbcur6.Text), true);
                if (tbcur7.Text != Share.defcur)
                    copyFile(tbcur7.Text, themeDir + @"Cursors\No" + Path.GetExtension(tbcur7.Text), true);
                if (tbcur8.Text != Share.defcur)
                    copyFile(tbcur8.Text, themeDir + @"Cursors\NWPen" + Path.GetExtension(tbcur8.Text), true);
                if (tbcur9.Text != Share.defcur)
                    copyFile(tbcur9.Text, themeDir + @"Cursors\SizeAll" + Path.GetExtension(tbcur9.Text), true);
                if (tbcur10.Text != Share.defcur)
                    copyFile(tbcur10.Text, themeDir + @"Cursors\SizeNESW" + Path.GetExtension(tbcur10.Text), true);
                if (tbcur11.Text != Share.defcur)
                    copyFile(tbcur11.Text, themeDir + @"Cursors\SizeNS" + Path.GetExtension(tbcur11.Text), true);
                if (tbcur12.Text != Share.defcur)
                    copyFile(tbcur12.Text, themeDir + @"Cursors\SizeNWSE" + Path.GetExtension(tbcur12.Text), true);
                if (tbcur13.Text != Share.defcur)
                    copyFile(tbcur13.Text, themeDir + @"Cursors\SizeWE" + Path.GetExtension(tbcur13.Text), true);
                if (tbcur14.Text != Share.defcur)
                    copyFile(tbcur14.Text, themeDir + @"Cursors\UpArrow" + Path.GetExtension(tbcur14.Text), true);
                if (tbcur15.Text != Share.defcur)
                    copyFile(tbcur15.Text, themeDir + @"Cursors\Wait" + Path.GetExtension(tbcur15.Text), true);

                //Sound

                for (int i = 0; i < sysWaveItems.Count; i++)
                {
                    if (sysWaveItems[i].Path != "" && sysWaveItems[i].Path != null)
                    {
                        string tempfilename = sysWaveItems[i].IniName.Remove(0, sysWaveItems[i].IniName.LastIndexOf("\\") + 1).Replace(".", "");

                        copyFile(sysWaveItems[i].Path, themeDir + @"Sound\" + tempfilename + ".wav", true);
                    }


                }

                //Wallpaper
                if (wps.Count != 0)
                {
                    for (int i = 0; i < wps.Count; i++)
                    {
                        copyFile(wps[i].Name, themeDir + @"Wallpapers\" + i.ToString() + Path.GetExtension(wps[i].Name), true);
                    }
                }

                return true;
            }
            catch (System.Exception ex)
            {
                showErrorWindow(ex.ToString());
                return false;
            }
        }

        //打开读取theme文件内容(2.5）
        private void readThemeFile()
        {
            var ini = new Class.IniFile(openThemeDir);
            string iniText = File.ReadAllText(openThemeDir, Encoding.Default);

            //theme
            tbThemeName.Text = ini.ReadInivalue("Theme", "DisplayName");
            tbFileName.Text = Path.GetFileNameWithoutExtension(ini.ReadInivalue("VisualStyles", "Path"));
            if (ini.ReadInivalue("Theme", "BrandImage") != "" && fest(relpaceSr(ini.ReadInivalue("Theme", "BrandImage"))))
                tbLogoDir.Text = relpaceSr(ini.ReadInivalue("Theme", "BrandImage"));
            if (fest(relpaceSr(ini.ReadInivalue("VisualStyles", "Path"))))
                tbMssfileDir.Text = relpaceSr(ini.ReadInivalue("VisualStyles", "Path"));

            tbInfo.Text = iniText.Remove(iniText.IndexOf("\n[") - 1).Replace(";", "").Replace("此主题文件由樱茶Win7主题生成器生成\r\n", "").Replace("\r\n\r\n", "");

            //icon
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\DefaultIcon", "DefaultValue")))))
                tbIconComputertfileDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\DefaultIcon", "DefaultValue")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon", "DefaultValue")))))
                tbIconUserDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon", "DefaultValue")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon", "DefaultValue")))))
                tbIconNetworkDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon", "DefaultValue")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Full")))))
                tbIconDustFullDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Full")));
            if (fest(removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Empty")))))
                tbIconDustEmptyDir.Text = removeico(relpaceSr(ini.ReadInivalue(@"CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon", "Empty")));

            //cursor
            string[] cur = new string[15];
            string[] tempCurString = { "AppStarting", "Arrow", "Crosshair", "Hand", "Help", "IBeam", "No", "NWPen", "SizeAll", "SizeNESW", "SizeNS", "SizeNWSE", "SizeWE", "UpArrow", "Wait" };
            for (int i = 0; i < 15; i++)
            {
                cur[i] = relpaceSr(ini.ReadInivalue(@"Control Panel\Cursors", tempCurString[i]));
            }
               
            for (int i = 1; i <= 15; i++)
            {
                if (fest(cur[i - 1]) && !cur[i - 1].ToLower().Contains((Environment.GetEnvironmentVariable("windir") + @"\cursors\").ToLower()))
                {
                    ((TextBox)FindName("tbcur" + i.ToString())).Text = cur[i - 1];
                    try
                    { ((TextBox)FindName("tbcur" + i.ToString())).Cursor = new System.Windows.Input.Cursor(cur[i - 1]); }
                    catch { }

                }
            }

            //wallpaper
            string wp0 = relpaceSr(ini.ReadInivalue(@"Control Panel\Desktop", "Wallpaper"));
            if (fest(wp0))
                wps.Add(new WallpaperItems { Name = wp0, Pic = wp0 });
            string sldir = relpaceSr(ini.ReadInivalue(@"Slideshow", "ImagesRootPath")) + "\\";
            if (Directory.Exists(sldir))
            {
                DirectoryInfo dir = new DirectoryInfo(sldir);
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    if ((Path.GetExtension(file.FullName).ToLower() == ".jpg"
                        || Path.GetExtension(file.FullName).ToLower() == ".png"
                        || Path.GetExtension(file.FullName).ToLower() == ".bmp"
                        || Path.GetExtension(file.FullName).ToLower() == ".jepg")
                        && file.FullName.ToLower() != wp0.ToLower())
                    {

                        if (!containWpsFile(file.FullName))
                            wps.Add(new WallpaperItems { Name = file.FullName, Pic = file.FullName });
                    }
                        
                }

            }

            if (wps.Count > 1)
            {
                cbWallpaperTime.IsEnabled = true;
                cbShuffle.IsEnabled = true;
            }
            else { cbWallpaperTime.IsEnabled = false; }

            if (ini.ReadInivalue(@"Slideshow", "Interval") != "")
            {
                int sltime = Convert.ToInt32(ini.ReadInivalue(@"Slideshow", "Interval"));
                for (int i = 0; i < sliderTime.Length; i++)
                {
                    if (sltime == sliderTime[i])
                        cbWallpaperTime.SelectedIndex = i;
                }
            }
            string shuffle = ini.ReadInivalue(@"Slideshow", "Shuffle");
            if (shuffle != "")
            {
                if (shuffle == "0")
                    cbShuffle.IsChecked = false;
                else
                    cbShuffle.IsChecked = true;
            }
            

            //color
            spectrumColorPicker.SelectedColor = (Color)ColorConverter.ConvertFromString("#" + ini.ReadInivalue(@"VisualStyles", "ColorizationColor").ToUpper().Replace("0X", ""));


            //sound
            bool isCustomWav = false;
            string soundThemeName = relpaceSr(ini.ReadInivalue("Sounds", "SchemeName"));
            if (Path.GetFileName(removedll(soundThemeName)) == "mmres.dll")
            {
                
                string num = soundThemeName.Remove(0, soundThemeName.LastIndexOf("-") + 1);
                int select = 0;
                for (int i = 0; i < cbSysWaveDefault.Items.Count; i++)
                {
                    if (num == cbSysWaveDefaultNum[i])
                        select = i;
                }
                cbSysWaveDefault.SelectedIndex = select;

            }
            else
            {
                for (int i = 0; i < sysWaveItems.Count; i++)
                {
                    string path = relpaceSr(ini.ReadInivalue(sysWaveItems[i].IniName, "DefaultValue"));
                    if (File.Exists(path))
                    {
                        sysWaveItems[i].Custom = "1";
                        sysWaveItems[i].Path = path;
                        isCustomWav = true;
                    }

                }
                listboxSysWaveItems.Items.Refresh();
                if (isCustomWav)
                {
                    chboxDefwav.IsChecked = false;
                    enableWave(true);
                }
            }


        }
        private bool containWpsFile(string str)
        {
            if (wps.Count != 0)
            {
                for (int i = 0; i < wps.Count; i++)
                {
                    if (wps[i].Name == str)
                        return true;

                }

                return false;
            }
            else
                return false;
        }
        private string relpaceSr(string str)//将%systemroot%转换为实际路径
        {
            return str.ToLower().Replace("%systemroot%", Environment.GetEnvironmentVariable("windir")).Replace("%resourcedir%", Environment.GetEnvironmentVariable("windir") + "\\resources");

        }
        private bool fest(string fullname)
        {
            if (File.Exists(fullname))
            { return true; }
            else
                return false;
        }
        private string removeico(string str)
        {
            //MessageBox.Show(str.LastIndexOf(".ico").ToString());
            if (str.LastIndexOf(".ico") < str.Length - 4)
                return str.Remove(str.IndexOf(".ico") + 4);
            else
                return str;

        }
        private string removedll(string str)
        {
            //MessageBox.Show(str.LastIndexOf(".ico").ToString());
            if (str.LastIndexOf(".dll") < str.Length - 4)
                return str.Remove(str.IndexOf(".dll") + 4);
            else
                return str;

        }

        //生成自解压文档（2.0）
        private void saveRar(string filename)
        {
            try
            {
                //MessageBox.Show(filename);
                string arg = " a -sfxdefault.sfx \"-z" + tempDir2 + "\"zhushi.txt" + " -r Files *.*";

                if (Directory.Exists(tempDir))
                { Directory.Delete(tempDir, true); }
                if (Directory.Exists(tempDir2))
                { Directory.Delete(tempDir2, true); }
                creatDir(tempDir);
                creatDir(tempDir2);
                writeFile();
                fileOperate(tempDir);
                string FILE_NAME = tempDir2 + "zhushi.txt";
                using (StreamWriter sw = new StreamWriter(new FileStream(FILE_NAME, FileMode.Create), System.Text.Encoding.Default))
                {
                    string zs = "Path=%SystemRoot%\\resources\\Themes\\\r\n";
                    if (checkboxSaveRarAutoRun.IsChecked.Value)
                        zs += "Setup=\"" + tbFileName.Text + ".theme\"\r\n";
                    if (tbSaveRarTitle.Text != "")
                        zs += "Title=" + tbSaveRarTitle.Text + "\r\n";
                    zs += "Text\r\n{\r\n" + tbSaveRarInfo.Text + "\r\n}\r\n";
                    if (checkboxSaveRarKey.IsChecked.Value)
                        zs += "License=\r\n{\r\n" + tbSaveRarKey.Text + "\r\n}\r\n";
                    sw.Write(zs);
                    sw.Close();
                }

                var startinfo = new ProcessStartInfo();
                startinfo.FileName = rarPath;
                startinfo.Arguments = arg;
                startinfo.WorkingDirectory = tempDir;
                Process proc = new Process();
                proc.StartInfo = startinfo;
                proc.Start();
                if (proc != null)
                {
                    proc.WaitForExit();
                }
                if (File.Exists(filename))
                    try { File.Delete(filename); }
                    catch (Exception ex) { showErrorWindow(ex.ToString()); }
                File.Move(tempDir + "Files.exe", filename);
                Directory.Delete(tempDir, true);
                Directory.Delete(tempDir2, true);
            }
            catch (System.Exception ex)
            {
                showErrorWindow(ex.ToString());
            }
        }

        //保存读取设置(1.5）
        GenSettings setting = new GenSettings();
        private bool isDef(string str)
        {
            if (str == Share.defcur || str == Share.defico || str == Share.defimg || str == Share.defwav || str == definfo || str == "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private void saveConfig()
        {
            //基本信息
            setting.tbMssfileDir = tbMssfileDir.Text;
            setting.tbLogoDir = tbLogoDir.Text;
            setting.tbInfo = tbInfo.Text;
            setting.tbThemeName = tbThemeName.Text;
            setting.tbFileName = tbFileName.Text;

            //图标
            setting.tbIconComputertfileDir = tbIconComputertfileDir.Text;
            setting.tbIconNetworkDir = tbIconNetworkDir.Text;
            setting.tbIconUserDir = tbIconUserDir.Text;
            setting.tbIconDustEmptyDir = tbIconDustEmptyDir.Text;
            setting.tbIconDustFullDir = tbIconDustFullDir.Text;

            //系统指针
            for (int i = 1; i <= 15; i++)
            {
                setting["tbcur" + i.ToString()] = ((TextBox)FindName("tbcur" + i.ToString())).Text;
            }

            //背景壁纸
            setting.lbWallPaperPlay = null;
            System.Collections.Specialized.StringCollection lbWallPaperPlayStrs = new System.Collections.Specialized.StringCollection();
            if (wps.Count != 0)
            {

                for (int i = 0; i < wps.Count; i++)
                {
                    lbWallPaperPlayStrs.Add(wps[i].Name);
                }
                setting.lbWallPaperPlay = lbWallPaperPlayStrs;
                setting.cbWallpaperTime = cbWallpaperTime.SelectedIndex;
                setting.cbShuffle = cbShuffle.IsChecked.Value;

            }

            //窗口颜色
            setting.tbColorStr = tbColorStr.Text;


            //系统音
            System.Collections.Specialized.StringCollection sysWaveTempItemsStr = new System.Collections.Specialized.StringCollection();
            sysWaveTempItemsStr.Clear();
            for (int i = 0; i < sysWaveItems.Count; i++)
            {
                sysWaveTempItemsStr.Add(null);
                sysWaveTempItemsStr[i] = sysWaveItems[i].Path;
            }
            setting.sysWave = sysWaveTempItemsStr;
            setting.chboxDefwav = chboxDefwav.IsChecked.Value;
            setting.cbSysWaveDefaultNum = cbSysWaveDefault.SelectedIndex;

            //自解压框
            setting.checkboxSaveRarKey = checkboxSaveRarKey.IsChecked.Value;
            setting.tbSaveRarKey = tbSaveRarKey.Text;
            setting.tbSaveRarInfo = tbSaveRarInfo.Text;
            setting.checkboxSaveRarAutoRun = checkboxSaveRarAutoRun.IsChecked.Value;
            setting.tbSaveRarTitle = tbSaveRarTitle.Text;
        }
        private void readConfig()
        {
            try
            {
                //基本信息
                if (!isDef(setting.tbMssfileDir))
                    tbMssfileDir.Text = setting.tbMssfileDir;
                if (!isDef(setting.tbLogoDir))
                    tbLogoDir.Text = setting.tbLogoDir;
                if (!isDef(setting.tbInfo))
                    tbInfo.Text = setting.tbInfo;
                if (!isDef(setting.tbThemeName))
                    tbThemeName.Text = setting.tbThemeName;
                if (!isDef(setting.tbFileName))
                    tbFileName.Text = setting.tbFileName;

                //系统图标
                if (!isDef(setting.tbIconComputertfileDir))
                    tbIconComputertfileDir.Text = setting.tbIconComputertfileDir;
                if (!isDef(setting.tbIconUserDir))
                    tbIconUserDir.Text = setting.tbIconUserDir;
                if (!isDef(setting.tbIconNetworkDir))
                    tbIconNetworkDir.Text = setting.tbIconNetworkDir;
                if (!isDef(setting.tbIconDustEmptyDir))
                    tbIconDustEmptyDir.Text = setting.tbIconDustEmptyDir;
                if (!isDef(setting.tbIconDustFullDir))
                    tbIconDustFullDir.Text = setting.tbIconDustFullDir;

                //系统指针
                for (int i = 1; i <= 15; i++)
                {
                    if (!isDef(setting["tbcur" + i.ToString()].ToString()))
                    {
                        ((TextBox)FindName("tbcur" + i.ToString())).Text = (string)setting["tbcur" + i.ToString()];
                        ((TextBox)FindName("tbcur" + i.ToString())).Cursor = new System.Windows.Input.Cursor((string)setting["tbcur" + i.ToString()]);
                    }
                }

                //背景壁纸
                System.Collections.Specialized.StringCollection wpstrs = new System.Collections.Specialized.StringCollection();
                wpstrs = setting.lbWallPaperPlay;
                if (wpstrs != null)
                {
                    for (int i = 0; i < wpstrs.Count; i++)
                    {
                        if (File.Exists(wpstrs[i]))
                            wps.Add(new WallpaperItems { Name = wpstrs[i], Pic = wpstrs[i] });
                    }
                    if (wpstrs.Count > 1)
                    {
                        cbShuffle.IsEnabled = true;
                        cbWallpaperTime.IsEnabled = true;
                    }

                }
                cbShuffle.IsChecked = setting.cbShuffle;
                cbWallpaperTime.SelectedIndex = setting.cbWallpaperTime;


                //窗口颜色
                spectrumColorPicker.SelectedColor = (Color)ColorConverter.ConvertFromString(setting.tbColorStr);


                //系统音
                if (setting.sysWave != null)
                {
                    System.Collections.Specialized.StringCollection sysWaveTempItemsStr = new System.Collections.Specialized.StringCollection();
                    sysWaveTempItemsStr.Clear();
                    sysWaveTempItemsStr = setting.sysWave;
                    for (int i = 0; i < sysWaveTempItemsStr.Count; i++)
                    {
                        if (File.Exists(sysWaveTempItemsStr[i]))
                        {
                            sysWaveItems[i].Custom = "1";
                            sysWaveItems[i].Path = sysWaveTempItemsStr[i];

                        }
                    }

                }
                chboxDefwav.IsChecked = setting.chboxDefwav;
                enableWave(!chboxDefwav.IsChecked.Value);
                cbSysWaveDefault.SelectedIndex = setting.cbSysWaveDefaultNum;

                //自解压框
                checkboxSaveRarKey.IsChecked = setting.checkboxSaveRarKey;
                if (setting.checkboxSaveRarKey)
                    tbSaveRarKey.IsEnabled = true;
                if (setting.tbSaveRarKey != "")
                    tbSaveRarKey.Text = setting.tbSaveRarKey;
                if (setting.tbSaveRarInfo != "")
                    tbSaveRarInfo.Text = setting.tbSaveRarInfo;
                checkboxSaveRarAutoRun.IsChecked = setting.checkboxSaveRarAutoRun;
                if (setting.tbSaveRarTitle != "")
                    tbSaveRarTitle.Text = setting.tbSaveRarTitle;
            }
            catch (Exception ex)
            {
                //throw new System.Exception("", ex);
                showErrorWindow(ex.ToString());
                setDefault();
            }
        }

        
        #endregion

        #region 事件相应
        // 工具按钮部分
        #region Tool Button

        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult mbr = MessageBox.Show("确定要新建吗？", "提示", MessageBoxButton.YesNo);
            if (mbr == MessageBoxResult.Yes)
            {
                setDefault();
            }
        }
   
        private void ShowOpenThemeFileWindowComplete(object sender, EventArgs e)
        {
            openThmeFile();
        }
        private void btnOpenThmeFileOk_Click(object sender, RoutedEventArgs e)
        {
            if (listboxOpenTheme.SelectedIndex != -1)
            {
                openThemeDir = themeDirFileItems[listboxOpenTheme.SelectedIndex].FullName;
                openTheme = File.ReadAllText(openThemeDir, Encoding.Default);

                if (cbDevTest.IsChecked == true)
                {
                    TestOutput testOutput = new TestOutput();
                    testOutput.tbTest.Text = openTheme;
                    testOutput.Show();
                }
                setDefault();
                HideOpenThemeFileWindow.Begin();
                try
                {

                    readThemeFile();
                }
                catch (System.Exception ex)
                {
                    showErrorWindow(ex.ToString());

                }


            }
        }
        private void btnOpenThmeFileDelete_Click(object sender, RoutedEventArgs e)
        {
            if (listboxOpenTheme.SelectedIndex != -1)
            {
                MessageBoxResult mbr = MessageBox.Show("确定要删除吗？", "提示", MessageBoxButton.YesNo);
                if (mbr == MessageBoxResult.Yes)
                {
                    
                }
            }
        }
        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            //已在Xaml处理，实现动画效果
        }

        private void listboxOpenTheme_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            btnOpenThmeFileOk_Click(null, null);
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            tbFileName.Text = tbFileName.Text.Trim();
            tbThemeName.Text = tbThemeName.Text.Trim();
            if (tbThemeName.Text == "" || tbMssfileDir.Text == "" || tbFileName.Text == "")
            {
                System.Windows.MessageBox.Show("信息不全，请注意填写带*号的选项", "错误", System.Windows.MessageBoxButton.OK);
            }
            else
            {
                MessageBoxResult mbr2 = MessageBox.Show("主题名称：" + this.tbThemeName.Text + "\r\n文件名称：" + tbFileName.Text + ".msstyles" + "\r\n壁纸数量：" + wps.Count.ToString() + "张" + "\r\n----------------------\r\n确定要保存到系统主题目录？", "提示", MessageBoxButton.YesNo);
                if (mbr2 == MessageBoxResult.Yes)
                {
                    writeFile();
                    if (cbDevTest.IsChecked == true)//是否为测试
                    {
                        TestOutput testOutput = new TestOutput();
                        testOutput.tbTest.Text = themeFile;
                        testOutput.ShowDialog();
                    }
                    else
                    {
                        try
                        {

                            string enname = tbFileName.Text;

                            if (Directory.Exists(sysThemeDir + enname + "\\") || File.Exists(sysThemeDir + enname + ".theme"))
                            {
                                MessageBoxResult mbr = MessageBox.Show("同名主题文件或文件夹已存在，是否要替换？", "覆盖提示", MessageBoxButton.YesNo);
                                if (mbr == MessageBoxResult.No)
                                    return;
                                else
                                {
                                    saveConfig();
                                    Application.Current.Shutdown();

                                    System.Diagnostics.Process.Start(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, "OverwriteSave");
                                    return;
                                }
                            }


                            save2();


                        }
                        catch (Exception ex)
                        {
                            showErrorWindow(ex.ToString());
                        }
                    }
                }
                
                
            }
        }
        private void save2()
        {
            string enname = tbFileName.Text;
            if (Directory.Exists(tempDir3))
            { Directory.Delete(tempDir3, true); }
            creatDir(tempDir3);

            if (fileOperate(tempDir3))
            {

                try
                {
                    if (File.Exists(sysThemeDir + enname + ".theme"))
                    {
                        File.Delete(sysThemeDir + enname + ".theme");
                    }
                    if (Directory.Exists(sysThemeDir + enname + "\\"))
                    {
                        Directory.Delete(sysThemeDir + enname + "\\", true);
                    }
                }
                catch
                {

                }


                DirectoryCopyX.DirectoryCopy(tempDir3 + enname + "\\", sysThemeDir + enname + "\\", true);
                File.Copy(tempDir3 + enname + ".theme", sysThemeDir + enname + ".theme", true);


                var mbr2 = MessageBox.Show("保存成功，是否打开主题目录？", "提示", MessageBoxButton.YesNo);
                if (mbr2 == MessageBoxResult.Yes)
                    try { System.Diagnostics.Process.Start("Explorer.exe", sysThemeDir); }
                    catch { }
            }
            Directory.Delete(tempDir3, true);
        }

        private void btnComExe_Click(object sender, RoutedEventArgs e)
        {
            if (Share.IsSaveRarCanvasOpen)
            {
                sbSaveRarClose.Begin();
                Share.IsSaveRarCanvasOpen = false;
            }
            else
            {
                sbSaveRarOpen.Begin();
                Share.IsSaveRarCanvasOpen = true;
            }
        }

        private void btnComResotre_Click(object sender, RoutedEventArgs e)
        {
            setDefault();
            try
            {
                readConfig();
            }
            catch(Exception ex)
            {
                showErrorWindow("读取设置错误！\r\n" + ex.ToString());
            }
        }
        private void btnHanaSpinSwitch_Click(object sender, RoutedEventArgs e)
        {
            AppSetting appSetting = new AppSetting();
            if (isAnimated)
            {
                sbNanaSpin.Pause();
                sbBigHnaSpin.Pause();
                SakuraFade.Pause();
                isAnimated = false;
                appSetting.IsAnimateRun = false;
                appSetting.Save();
            }
            else
            {
                sbNanaSpin.Resume();
                sbBigHnaSpin.Resume();
                SakuraFade.Resume();
                isAnimated = true;
                appSetting.IsAnimateRun = true;
                appSetting.Save();
            }
        }
        #endregion

        // 主题信息部分
        #region Styles Infomation

        


        private void btnLogo_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir(tbLogoDir, "png");
        }

        private void btnLogoBack_Click(object sender,RoutedEventArgs e)
        {
            tbLogoDir.Text = Share.defimg;
        }

        private void tbInfo_TextChanged(object sender, TextChangedEventArgs e)
        {
            
        }

        private void tbThemeName_LostFocus(object sender, RoutedEventArgs e)
        {
            replaceFileName(tbThemeName);
        }

        private void tbFileName_TextChanged(object sender, TextChangedEventArgs e)
        {
            replaceFileName(tbFileName);
        }

        #endregion

        #region Msstyles


        private void btnMssfile_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir(tbMssfileDir, "mss");

        }
        private void btnMssFileDefaut_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists(sysThemeDir + "Aero\\aero.msstyles"))
                tbMssfileDir.Text = sysThemeDir + "Aero\\aero.msstyles";
        }



        private void btnOpenStylebuilder_Click(object sender, RoutedEventArgs e)
        {
            AppSetting appSetting = new AppSetting();
            if (appSetting.WSBDir == null || appSetting.WSBDir == "" || !File.Exists(appSetting.WSBDir))
            {
                MessageBox.Show("尚未设置Win7StyleBuilder的位置，请设置");
                btnOpenStylebuilderSetting_Click(null, null);
            }
            else
            {
                try { System.Diagnostics.Process.Start("Explorer.exe", appSetting.WSBDir); }
                catch { }
            }
        }

        private void btnOpenStylebuilderSetting_Click(object sender, RoutedEventArgs e)
        {
            AppSetting appSetting = new AppSetting();
            OpenFileDialog op = new OpenFileDialog();
            op.RestoreDirectory = true;
            op.Filter = " 应用程序|*.exe";
            op.ShowDialog();
            if (op.FileName != "")
            {
                appSetting.WSBDir = op.FileName;
                appSetting.Save();
            }
        }
        #endregion 

        // 系统图标部分
        #region Sytem Icons

        private void btnIconComputer_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir(tbIconComputertfileDir, "ico");
        }

        private void btnIconUser_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir(tbIconUserDir, "ico");
        }

        private void btnIconNetwork_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir(tbIconNetworkDir, "ico");
        }

        private void btnIconDustEmpty_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir(tbIconDustEmptyDir, "ico");
        }

        private void btnIconDustFull_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir(tbIconDustFullDir, "ico");
        }

        private void btnIconComputerBack_Click(object sender, RoutedEventArgs e)
        {
            tbIconComputertfileDir.Text = Share.defico;
        }

        private void btnIconUserBack_Click(object sender, RoutedEventArgs e)
        {
            tbIconUserDir.Text = Share.defico;
        }

        private void btnIconNetworkBack_Click(object sender, RoutedEventArgs e)
        {
            tbIconNetworkDir.Text = Share.defico;
        }

        private void btnIconDustEmptyBack_Click(object sender, RoutedEventArgs e)
        {
            tbIconDustEmptyDir.Text = Share.defico;
        }

        private void btnIconDustFullBack_Click(object sender, RoutedEventArgs e)
        {
            tbIconDustFullDir.Text = Share.defico;
        }

        

        #endregion

        // 鼠标指针部分
        #region Mouse Cursor

        
        private void btnCur1_Click(object sender, RoutedEventArgs e)
        {
             
            fileDialogDir((TextBox)FindName("tbcur1"), "cur");
        }

        private void btnCur2_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur2"), "cur");
        }

        private void btnCur3_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur3"), "cur");
        }

        private void btnCur4_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur4"), "cur");
        }

        private void btnCur5_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur5"), "cur");
        }

        private void btnCur6_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur6"), "cur");
        }

        private void btnCur7_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur7"), "cur");
        }

        private void btnCur8_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur8"), "cur");
        }

        private void btnCur9_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur9"), "cur");
        }

        private void btnCur10_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur10"), "cur");
        }

        private void btnCur11_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur11"), "cur");
        }

        private void btnCur12_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur12"), "cur");
        }

        private void btnCur13_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur13"), "cur");
        }

        private void btnCur14_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur14"), "cur");
        }

        private void btnCur15_Click(object sender, RoutedEventArgs e)
        {
            fileDialogDir((TextBox)FindName("tbcur15"), "cur");
        }

        #region 暂时不用

        private void tbcur1_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur2_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur3_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur4_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur5_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur6_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur7_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur8_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur9_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur10_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur11_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur12_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur13_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur14_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void tbcur15_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
#endregion

        private void btnCurDel1_Click(object sender, RoutedEventArgs e)
        {
            tbcur1.Text = Share.defcur;
            tbcur1.Cursor = System.Windows.Input.Cursors.AppStarting;
        }
        private void btnCurDel2_Click(object sender, RoutedEventArgs e)
        {
            tbcur2.Text = Share.defcur;
            tbcur2.Cursor = System.Windows.Input.Cursors.Arrow;
        }
        private void btnCurDel3_Click(object sender, RoutedEventArgs e)
        {
            tbcur3.Text = Share.defcur;
            tbcur3.Cursor = System.Windows.Input.Cursors.Cross;
        }
        private void btnCurDel4_Click(object sender, RoutedEventArgs e)
        {
            tbcur4.Text = Share.defcur;
            tbcur4.Cursor = System.Windows.Input.Cursors.Hand;
        }
        private void btnCurDel5_Click(object sender, RoutedEventArgs e)
        {
            tbcur5.Text = Share.defcur;
            tbcur5.Cursor = System.Windows.Input.Cursors.Help;
        }
        private void btnCurDel6_Click(object sender, RoutedEventArgs e)
        {
            tbcur6.Text = Share.defcur;
            tbcur6.Cursor = System.Windows.Input.Cursors.IBeam;
        }
        private void btnCurDel7_Click(object sender, RoutedEventArgs e)
        {
            tbcur7.Text = Share.defcur;
            tbcur7.Cursor = System.Windows.Input.Cursors.No;
        }
        private void btnCurDel8_Click(object sender, RoutedEventArgs e)
        {
            tbcur8.Text = Share.defcur;
            tbcur8.Cursor = System.Windows.Input.Cursors.Pen;
        }
        private void btnCurDel9_Click(object sender, RoutedEventArgs e)
        {
            tbcur9.Text = Share.defcur;
            tbcur9.Cursor = System.Windows.Input.Cursors.SizeAll;
        }
        private void btnCurDel10_Click(object sender, RoutedEventArgs e)
        {
            tbcur10.Text = Share.defcur;
            tbcur10.Cursor = System.Windows.Input.Cursors.SizeNESW;
        }
        private void btnCurDel11_Click(object sender, RoutedEventArgs e)
        {
            tbcur11.Text = Share.defcur;
            tbcur11.Cursor = System.Windows.Input.Cursors.SizeNS;
        }
        private void btnCurDel12_Click(object sender, RoutedEventArgs e)
        {
            tbcur12.Text = Share.defcur;
            tbcur12.Cursor = System.Windows.Input.Cursors.SizeNWSE;
        }
        private void btnCurDel13_Click(object sender, RoutedEventArgs e)
        {
            tbcur13.Text = Share.defcur;
            tbcur13.Cursor = System.Windows.Input.Cursors.SizeWE;
        }
        private void btnCurDel14_Click(object sender, RoutedEventArgs e)
        {
            tbcur14.Text = Share.defcur;
            tbcur14.Cursor = System.Windows.Input.Cursors.UpArrow;
        }
        private void btnCurDel15_Click(object sender, RoutedEventArgs e)
        {
            tbcur15.Text = Share.defcur;
            tbcur15.Cursor = System.Windows.Input.Cursors.Wait;
        }
        #endregion

        // 壁纸部分
        #region Wallpapers

        private void btnWallPaperPlayAdd_Click(object sender, RoutedEventArgs e)
        {
            addWallpaper();
            
            
        }
        private void WallPaperPlayClr_Click(object sender, RoutedEventArgs e)
        {
            wps.Clear();
            
        }

        private void lbWallPaperPlay_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {

        }

        private void btnWallpaperUp_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (listboxWallpaperItems.SelectedIndex > 0)
                {
                    object obj = wps[listboxWallpaperItems.SelectedIndex];
                    int set = listboxWallpaperItems.SelectedIndex;
                    wps.RemoveAt(listboxWallpaperItems.SelectedIndex);
                    wps.Insert(set - 1, (WallpaperItems)obj);
                    listboxWallpaperItems.SelectedIndex = set - 1;

                }

            }
            catch { }
            listboxWallpaperItems.Focus();
            
        }
        private void btnWallpaperDown_Click(object sender, RoutedEventArgs e)
        {
            
            try
            {
                if (listboxWallpaperItems.SelectedIndex < listboxWallpaperItems.Items.Count - 1 && listboxWallpaperItems.SelectedIndex != -1)
                {
                    object obj = wps[listboxWallpaperItems.SelectedIndex];
                    int set = listboxWallpaperItems.SelectedIndex;
                    wps.RemoveAt(listboxWallpaperItems.SelectedIndex);
                    wps.Insert(set + 1, (WallpaperItems)obj);
                    listboxWallpaperItems.SelectedIndex = set + 1;
                    
                }

            }
            catch { }
            listboxWallpaperItems.Focus();
        }
        void listboxWallpaperItems_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                btnWallpaperDel_Click(null, null);
            }
        }
        private void btnWallpaperDel_Click(object sender, RoutedEventArgs e)
        {
            if (wps.Count != 0)
            {
                int set = listboxWallpaperItems.SelectedIndex;
                wps.RemoveAt(set);
                try
                {
                    if (wps.Count != set) listboxWallpaperItems.SelectedIndex = set;
                    else listboxWallpaperItems.SelectedIndex = set - 1;
                }
                catch { }
                listboxWallpaperItems.Focus();

            }
            
        }
        private void listboxWallpaperItems_MouseDoubleClick_1(object sender, MouseButtonEventArgs e)
        {
            if (listboxWallpaperItems.SelectedIndex != -1)
            {
                BitmapImage bmpgPreview = new BitmapImage(new Uri(wps[listboxWallpaperItems.SelectedIndex].Name, UriKind.Absolute));
                setImage(imgPicView, wps[listboxWallpaperItems.SelectedIndex].Name);
                imgPicView.Source = bmpgPreview;
                lbPicViewInfo.Text = "图像尺寸：" + bmpgPreview.PixelWidth.ToString() + "*" + bmpgPreview.PixelHeight.ToString();
                FileInfo fileInfo = new FileInfo(wps[listboxWallpaperItems.SelectedIndex].Name);
                lbPicViewInfo.Text += "  大小：" + fileInfo.Length / 1024 + "KB";

                ShowPicViewWindow.Begin();
            }
        }

        //拖入文件
        void listboxWallpaperItems_DragEnter(object sender, DragEventArgs e)
        {
            //判断拖入的对象格式
            if (e.Data.GetDataPresent(DataFormats.FileDrop, true) == true)
            {
                //允许拖放
                e.Effects = DragDropEffects.All;
            }

        }
        void listboxWallpaperItems_Drop(object sender, DragEventArgs e)
        {
            //获取文件列表（文件夹会被当作文件处理）
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string filename in files)
            {
                FileInfo fi = new FileInfo(filename);
                if (fi.Extension.ToLower() == ".jpg" || fi.Extension == ".png" || fi.Extension == ".bmp" || fi.Extension == ".gif" )
                {
                    wps.Add(new WallpaperItems { Name = filename, Pic = filename });
                }
            }
            
        }

        #endregion

        // 系统颜色部分
        #region Style Colors

        
        
        #endregion

        // 系统音部分
        #region System Wave

        
        
        private void btnSysWaveChoose_Click(object sender, RoutedEventArgs e)
        {
            if (listboxSysWaveItems.SelectedIndex != -1)
            {
                fileDialogDir(tbSysWavePath, "wav");
                if (tbSysWavePath.Text != "" && tbSysWavePath.Text != Share.defwav)
                {
                    sysWaveItems[listboxSysWaveItems.SelectedIndex].Path = tbSysWavePath.Text;
                    sysWaveItems[listboxSysWaveItems.SelectedIndex].Custom = "1";
                    listboxSysWaveItems.Items.Refresh();
                }
            }
        }

        private void btnSysWavePlay_Click(object sender, RoutedEventArgs e)
        {
            if (tbSysWavePath.Text != Share.defwav && File.Exists(tbSysWavePath.Text))
            {
                using (SoundPlayer player = new SoundPlayer(tbSysWavePath.Text))
                {
                    player.Play();
                }
            }
        }

        private void listboxSysWaveItems_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (File.Exists(sysWaveItems[listboxSysWaveItems.SelectedIndex].Path))
            {
                tbSysWavePath.Text = sysWaveItems[listboxSysWaveItems.SelectedIndex].Path;


            }
            else
            {
                tbSysWavePath.Text = Share.defwav;

            }
        }


        private void chboxDefwav_Click(object sender, RoutedEventArgs e)
        {
            if (chboxDefwav.IsChecked.Value)
            {
                enableWave(false);
            }
            else
            {
                enableWave(true);
            }
        }

        private void enableWave(bool b)
        {
            cbSysWaveDefault.IsEnabled = !b;
            listboxSysWaveItems.IsEnabled = b;
            tbSysWavePath.IsEnabled = b;
            btnSysWavePlay.IsEnabled = b;
            btnSysWaveChoose.IsEnabled = b;
            btnSysWaveDel.IsEnabled = b;
        }

        private void btnSysWaveDel_Click(object sender, RoutedEventArgs e)
        {
            if (listboxSysWaveItems.SelectedIndex != -1)
            {
                sysWaveItems[listboxSysWaveItems.SelectedIndex].Path = null;
                sysWaveItems[listboxSysWaveItems.SelectedIndex].Custom = "0";
                tbSysWavePath.Text = Share.defwav;
                listboxSysWaveItems.Items.Refresh();
            }
        }
        private void listboxSysWaveItems_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            btnSysWavePlay_Click(null, null);
        }

        #endregion

        // 保存自解压窗口
        #region Saving Rar File Window

        private void btnComExeOK_Click(object sender, RoutedEventArgs e)
        {
            tbFileName.Text = tbFileName.Text.Trim();
            tbThemeName.Text = tbThemeName.Text.Trim();
            if (tbThemeName.Text == "" || tbMssfileDir.Text == "" || tbFileName.Text == "")
            {
                System.Windows.MessageBox.Show("信息不全，请注意带*号的选项", "错误", System.Windows.MessageBoxButton.OK);
            }
            else
            {

                SaveFileDialog sp = new SaveFileDialog();
                sp.RestoreDirectory = true;
                sp.Filter = "自解压文件(*.exe)|*.exe";
                sp.ShowDialog();
                if (sp.FileName != "")
                {
                    saveRar(sp.FileName);
                }
            }
        }

        private void btnComExeCancel_Click(object sender, RoutedEventArgs e)
        {
            sbSaveRarClose.Begin();
            Share.IsSaveRarCanvasOpen = false;
        }

        private void checkboxSaveRarKey_Click(object sender, RoutedEventArgs e)
        {
            if (checkboxSaveRarKey.IsChecked == true)
            { tbSaveRarKey.IsEnabled = true; }
            else
            { tbSaveRarKey.IsEnabled = false; }
        }
        #endregion

        #region Other

        void wps_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            detectWallpaperNum();
        }

        //退出前
        private void winMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            saveConfig();
            setting.Save();
        }


        //鼠标拖动窗口
        private void GlassWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                DragMove();
            }
            catch { }
        }

        //按下按键（测试用）
        private void GlassWindow_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F9)
            {
                if (cbDevTest.Visibility == Visibility.Hidden)
                {
                    cbDevTest.Visibility = Visibility.Visible;


                }
                else
                {
                    cbDevTest.Visibility = Visibility.Hidden;
                }
                
            }
            if (e.Key == Key.F8)
            {
                showErrorWindow("    其实没有出错啦。你看到这个画面说明你按到F8啦。很无聊啊很无聊，这些都是拿来测试用的，算是彩蛋吧，你按到F9也会有东西出来~做软件其实还是挺麻烦的。这个软件弄坏了很久啊，都不知道花了多长时间来搞的。总之就是有兴趣花多少时间都不会觉得乏味，以后工作的时候也是这样的，感兴趣的东西你就会不辞辛劳的做好它。相对的，你不喜欢的东西你就会对它产生不良情绪，波及到你做事的结果。\r\n   欢迎访问我的主页~");
            }
            if (e.Key == Key.F6)
            {
                
            }
        }
        #endregion

        


        #endregion

    }
}
